#coding:utf-8
import time,os,logging
from str2arry import str2arry
from serialCom import serialCom
from checkSum import hex_checksum

FILE = os.getcwd()          #返回当前目录的路径
#logging基础配置，文件名为 os.path.join里面的两个值想加个，输出等级为≥DEBUG级别
logging.basicConfig(filename = os.path.join(FILE,'log.txt'),level = logging.DEBUG,
                    format='%(asctime)s %(filename)s [line:%(lineno)d] %(levelname)s %(message)s')

def setG(G):
    print '----------------------------------------------------------'
    print 'case3 设置规格' + '\n' + '                                    '
    logging.debug('*****case 3设置额定流量*****')
    # 设置额定流量，格式
    setGfirst = 'FE FE FE FE FE 68 AB 57 58'
    # meterID[i]
    setGmid = 'F2 77 88 99 55 04 00 06 A0 22 01 00 00'
    # G={'02':'1.6方','03':'2.5方','04':'4方','05':'6方','06':'10方','07':'16方','08':'25方','09': '40方', '0A':'65方', '0B':'宽量程'}

    # 校验和
    # 16
    # 读取表号
    meterIDread = (
        ''.join(('FE FE FE FE FE 68 AB 57 58 AA AA AA AA AA F2 77 88 99 55 03 00 03 81 0A 01 85 16').split()))
    ID = serialCom(meterIDread, 35)[28:38]
    ID = str2arry(ID)
    # 读取表号
    for n in sorted(G.keys()):
        setGdata = setGfirst.split() + ID + setGmid.split() + n.split()
        setGcheckSum = hex_checksum(setGdata[5:])
        setGsend = ''.join(setGdata + setGcheckSum + ['16'])

        print '设置规格' + G[n] + ',',

        serialCom(setGsend)


        # 读取额定流量，格式
        readGfirst = 'FE FE FE FE FE 68 AB 57 58'
        # meterID[i]
        readGmid = 'F2 77 88 99 55 01 00 03 81 0C 01'
        # 校验和
        # 16

        readGdata = readGfirst.split() + ID + readGmid.split()
        readGcheckSum = hex_checksum(readGdata[5:])
        readGsend = ''.join(readGdata + readGcheckSum + ['16'])

        G_receive = serialCom(readGsend, 36)

        G_receive = str2arry(G_receive)

        G_receiveCheckSum = G_receive[28]

        if G_receiveCheckSum.split()== hex_checksum(G_receive[5:28]):  # 对接收到的数据进行校验
            if G_receive[27] == n:

                print G[n] + '设置成功'
                logging.debug('设置%s成功'%G[n])
            else:
                print G[n]+'设置失败'
                logging.debug('设置%s失败' % G[n])


        else:
            print '数据异常'
            logging.debug('数据异常')



